package com.sinodata.bsm.center.web.action.event;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.EventBean;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.web.action.BaseExportAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-8 上午10:51:32          liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class EventHisExportAction extends BaseExportAction<Event> {

    /**
     * 
     */
    private static final long serialVersionUID = -9093862064529134796L;

    @Autowired
    private EventService eventService;

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseExportAction#doExport()
     */
    @Override
    public String doExport() throws Exception {
        String fileName = "查看事件";
        String displayFileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
        response.setContentType("APPLICATION/msexcel; charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + displayFileName.trim().replaceAll("\\s", "") + ".xls\"");

        HSSFSheet sheet = workBook.createSheet("查看事件");
        //设置列的宽度  
        sheet.setColumnWidth(0, 4000);
        sheet.setColumnWidth(1, 8000);
        sheet.setColumnWidth(2, 8000);
        sheet.setColumnWidth(3, 4000);
        sheet.setColumnWidth(4, 20000);
        sheet.setColumnWidth(5, 5000);
        sheet.setColumnWidth(6, 4000);
        sheet.setColumnWidth(7, 5000);
        sheet.setColumnWidth(8, 4000);
        sheet.setColumnWidth(9, 5000);
        sheet.setColumnWidth(10, 4000);
        sheet.setColumnWidth(11, 5000);

        //表头
        HSSFCellStyle style = getStyle(STYLE_HEADING);
        HSSFRow rowHead = sheet.createRow(0);
        HSSFCell ipHead = rowHead.createCell(0);
        ipHead.setCellValue(new HSSFRichTextString("IP地址"));
        ipHead.setCellStyle(style);
        HSSFCell resNameHead = rowHead.createCell(1);
        resNameHead.setCellValue(new HSSFRichTextString("资源名称"));
        resNameHead.setCellStyle(style);
        HSSFCell eventTypeNameHead = rowHead.createCell(2);
        eventTypeNameHead.setCellValue(new HSSFRichTextString("事件类别"));
        eventTypeNameHead.setCellStyle(style);
        HSSFCell msgHead = rowHead.createCell(3);
        msgHead.setCellValue(new HSSFRichTextString("事件级别"));
        msgHead.setCellStyle(style);
        HSSFCell levelNameHead = rowHead.createCell(4);
        levelNameHead.setCellValue(new HSSFRichTextString("事件内容"));
        levelNameHead.setCellStyle(style);
        HSSFCell occurTimeHead = rowHead.createCell(5);
        occurTimeHead.setCellValue(new HSSFRichTextString("产生时间"));
        occurTimeHead.setCellStyle(style);
        HSSFCell ackHead = rowHead.createCell(6);
        ackHead.setCellValue(new HSSFRichTextString("认领人"));
        ackHead.setCellStyle(style);
        HSSFCell ackTimeHead = rowHead.createCell(7);
        ackTimeHead.setCellValue(new HSSFRichTextString("认领时间"));
        ackTimeHead.setCellStyle(style);
        HSSFCell confirmHead = rowHead.createCell(8);
        confirmHead.setCellValue(new HSSFRichTextString("清除人"));
        confirmHead.setCellStyle(style);
        HSSFCell confirmTimeHead = rowHead.createCell(9);
        confirmTimeHead.setCellValue(new HSSFRichTextString("清除时间"));
        confirmTimeHead.setCellStyle(style);
        HSSFCell countHead = rowHead.createCell(10);
        countHead.setCellValue(new HSSFRichTextString("检测次数"));
        countHead.setCellStyle(style);
        HSSFCell lastOccurTimeHead = rowHead.createCell(11);
        lastOccurTimeHead.setCellValue(new HSSFRichTextString("最后刷新时间"));
        lastOccurTimeHead.setCellStyle(style);

        //查询条件
        String resIdSearchScope = request.getParameter("resId");
        String resIdAllScope = (resIdSearchScope == null || resIdSearchScope.equals("")) ? "" : resIdSearchScope;
        String dimension = request.getParameter("dimension");
        String level = request.getParameter("level");
        String eventTypeId = request.getParameter("eventTypeId");
        String status = request.getParameter("status");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        String confirmtype = request.getParameter("confirmtype");
        String confirmer = request.getParameter("confirmer");
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        //当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        if (resIds.toString() != null && !resIds.toString().equals("")) {
            String userId = UserUtil.getInstance().getCurrentUserId();
            if (!UserUtil.getInstance().isSysAdmin(userId) && !UserUtil.getInstance().isGuest(userId)) {//guest用户有全部数据的查看权限
                if (resIdAllScope.equals("")) {
                    resIdAllScope = resIds.toString();
                }
                //                } else {
                //                    resIdAllScope = resIdAllScope + "," + resIds.toString();
                //                }
            }
        } else {
            workBook.write(response.getOutputStream());
            return null;
        }
        if (level != null && !level.equals("")) {
            map.put("level_", level);
        } else {
            map.put("level_", "-1");
        }
        if (eventTypeId != null && !eventTypeId.equals("-1")) {
            map.put("res_type_id", eventTypeId);
        }
        if (beginDate != null && !beginDate.equals("")) {
            map.put("beginDate", beginDate);
        }
        if (endDate != null && !endDate.equals("")) {
            map.put("endDate", endDate);
        }
        if (status != null && !status.equals("")) {
            map.put("status", status);
        } else {
            map.put("status", "-1");
        }
        if (confirmtype != null && !confirmtype.equals("")) {
            map.put("confirm_type", confirmtype);
        }
        if (confirmer != null && !confirmer.equals("")) {
            map.put("confirmer", "'" + confirmer + "'");
        }
        //资源ID条件
        if (!resIdAllScope.equals("")) {
            map.put("resIds", resIdAllScope);
        }
        map.put("CATALOG", String.valueOf(EventConstants.CATALOG_FAULTEVENT));
        map.put("filter_event_id", null);
        condition.setWhere(map);

        List<EventBean> list = eventService.findEventByCondition(condition, dimension);
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        //表体赋值
        style = getStyle(STYLE_CONTENT);
        int rowNum = 1;

        for (EventBean eventBean : list) {
            HSSFRow row = sheet.createRow(rowNum++);
            HSSFCell ip = row.createCell(0);
            ip.setCellValue(new HSSFRichTextString(eventBean.getIp()));
            HSSFCell resName = row.createCell(1);
            //寻找父资源
            Res parent = null;
            List<ResBean> resBeans = RelationHelper.parents(eventBean.getEvent().getResId());
            if (resBeans.size() > 0) {
                parent = resBeans.get(0).res();
            }
            StringBuffer parentNameValue = new StringBuffer("");
            parentNameValue.append(parent == null ? "" : parent.getName() + "/");
            parentNameValue.append(eventBean.getResName());
            resName.setCellValue(new HSSFRichTextString(parentNameValue.toString()));
            HSSFCell eventTypeName = row.createCell(2);
            eventTypeName.setCellValue(new HSSFRichTextString(eventBean.getEventTypeName()));
            HSSFCell levelName = row.createCell(3);
            levelName.setCellValue(new HSSFRichTextString(EventConstants.getLevelDesc(eventBean.getEvent().getLevel())));
            HSSFCell msg = row.createCell(4);
            msg.setCellValue(new HSSFRichTextString(eventBean.getEvent().getMsg()));
            HSSFCell occurTime = row.createCell(5);
            occurTime.setCellValue(new HSSFRichTextString(eventBean.getOccurTime()));
            HSSFCell ack = row.createCell(6);
            ack.setCellValue(new HSSFRichTextString(eventBean.getEvent().getAckUser() == null ? "" : (UserUtil.getInstance().getUserById(eventBean.getEvent().getAckUser()) == null ? eventBean.getEvent().getAckUser() + "此用户已删除" : UserUtil.getInstance().getUserById(eventBean.getEvent().getAckUser()).getFullName())));
            HSSFCell ackTime = row.createCell(7);
            ackTime.setCellValue(new HSSFRichTextString(eventBean.getEvent().getAckTime() == null ? "" : simple.format(eventBean.getEvent().getAckTime())));
            HSSFCell confirm = row.createCell(8);
            if (eventBean.getEvent().getConfirmType() != null && eventBean.getEvent().getConfirmType().equals(EventConstants.CONFIRM_TYPE_USER)) {
                confirm.setCellValue(new HSSFRichTextString(eventBean.getEvent().getConfirmer() == null ? "" : (UserUtil.getInstance().getUserById(eventBean.getEvent().getConfirmer()) == null ? eventBean.getEvent().getConfirmer() + "此用户已删除" : UserUtil.getInstance().getUserById(eventBean.getEvent().getConfirmer()).getFullName())));
            } else {
                confirm.setCellValue(new HSSFRichTextString(eventBean.getEvent().getConfirmer() == null ? "" : "system"));
            }
            HSSFCell confirmTime = row.createCell(9);
            confirmTime.setCellValue(new HSSFRichTextString(eventBean.getEvent().getConfirmTime() == null ? "" : simple.format(eventBean.getEvent().getConfirmTime())));
            HSSFCell count = row.createCell(10);
            count.setCellValue(eventBean.getEvent().getCount() == null ? new HSSFRichTextString("") : new HSSFRichTextString(String.valueOf(eventBean.getEvent().getCount())));
            HSSFCell lastOccurTime = row.createCell(11);
            lastOccurTime.setCellValue(new HSSFRichTextString((eventBean.getLastOccurTime() == null) ? "" : eventBean.getLastOccurTime()));
            if (rowNum % 2 != 0) {
                resName.setCellStyle(style);
                eventTypeName.setCellStyle(style);
                msg.setCellStyle(style);
                levelName.setCellStyle(style);
                occurTime.setCellStyle(style);
                ack.setCellStyle(style);
                ackTime.setCellStyle(style);
                confirm.setCellStyle(style);
                confirmTime.setCellStyle(style);
                count.setCellStyle(style);
                lastOccurTime.setCellStyle(style);
            }
        }
        workBook.write(response.getOutputStream());
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        return null;
    }

}
